package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.wemedia.IWemediaClient;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.HotArticleService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.vos.HotArticleVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmChannel;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class HotArticleServiceImpl implements HotArticleService {

    @Autowired
    private ApArticleMapper apArticleMapper;

    /**
     * 计算热点文章 带分数  5天前
     */
    @Override
    public void computeHotArticle() {
        //从数据库中查询文章
        // 构造五天前的时间
        Date lastFiveDate = DateTime.now().minusDays(5).toDate();
        //从数据库中查询五天前的热点文章
        List<ApArticle> articleListByLast5days = apArticleMapper.findArticleListByLast5days(lastFiveDate);
        // 根据阅读 点赞 评论 收藏计算 五天前的文章分数
        //2.计算文章的分值
        if (CollectionUtils.isEmpty(articleListByLast5days)) {
            return;
        }
        List<HotArticleVo> hotArticleVoList = computeHotArticleScore(articleListByLast5days);
        //将 每个频道前30条文章存入redis缓存中并降序排序  key为前缀+ 频道id
        cacheTagToRedis(hotArticleVoList);

    }

    @Autowired
    private IWemediaClient wemediaClient;

    /**
     * 将 每个频道前30条文章存入redis缓存中并降序排序  key为前缀+ 频道id
     *
     * @param hotArticleVoList
     */
    private void cacheTagToRedis(List<HotArticleVo> hotArticleVoList) {
        // 调用自媒体端 Feign 查询频道信息
        ResponseResult channelsResponse = wemediaClient.getChannels();
        // 判断是否成功
        if (channelsResponse.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())) {
            String channelsJSONString = JSON.toJSONString(channelsResponse.getData());
            // 获取自媒体频道信息集合
            List<WmChannel> wmChannelList = JSON.parseArray(channelsJSONString, WmChannel.class);
            if (!CollectionUtils.isEmpty(wmChannelList)) {
                //检索出每个频道的文章
                for (WmChannel wmChannel : wmChannelList) {
                    List<HotArticleVo> hotArticleVos = hotArticleVoList.stream().filter(hotArticleVo -> hotArticleVo.getChannelId() == wmChannel.getId()).collect(Collectors.toList());

                    //给文章进行排序，取30条分值较高的文章存入redis  key：前缀+频道id   value：30条分值较高的文章
                    sortAndCache(hotArticleVos, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + wmChannel.getId());
                }
            }
        }

        //设置推荐数据（没有存在频道）
        //给文章进行排序，取30条分值较高的文章存入redis  key：前缀+__all__   value：30条分值较高的文章
        sortAndCache(hotArticleVoList, ArticleConstants.HOT_ARTICLE_FIRST_PAGE + ArticleConstants.DEFAULT_TAG);
    }

    @Autowired
    private CacheService cacheService;

    /**
     * 给文章进行排序，取30条分值较高的文章存入redis  key：前缀+频道id   value：30条分值较高的文章
     *
     * @param hotArticleVos
     * @param key
     */
    private void sortAndCache(List<HotArticleVo> hotArticleVos, String key) {
        if (!CollectionUtils.isEmpty(hotArticleVos)) {
            // 按分数降序排序并过滤出前30条文章 并存入redis
            hotArticleVos = hotArticleVos.stream().sorted(Comparator.comparing(HotArticleVo::getScore).reversed()).limit(30).collect(Collectors.toList());
            cacheService.set(key, JSON.toJSONString(hotArticleVos));
        }
    }

    /**
     * 计算文章的分数
     *
     * @param articleListByLast5days
     * @return
     */
    private List<HotArticleVo> computeHotArticleScore(List<ApArticle> articleListByLast5days) {
        List<HotArticleVo> hotArticleVoList = new ArrayList<>();
        if (CollectionUtils.isEmpty(articleListByLast5days)) {
            return hotArticleVoList;
        }
        for (ApArticle apArticle : articleListByLast5days) {
            // 获取每个文章的分数
            Integer score = computeScore(apArticle);
            HotArticleVo hotArticleVo = new HotArticleVo();
            BeanUtils.copyProperties(apArticle, hotArticleVo);
            hotArticleVo.setScore(score);
            hotArticleVoList.add(hotArticleVo);
        }
        return hotArticleVoList;
    }

    private Integer computeScore(ApArticle apArticle) {
        Integer score = 0;

        //阅读  *1
        if (apArticle.getViews() != null) {
            score += apArticle.getViews();
        }
        //点赞  *3
        if (apArticle.getLikes() != null) {
            score += apArticle.getLikes() * ArticleConstants.HOT_ARTICLE_LIKE_WEIGHT;
        }
        //评论  *5
        if (apArticle.getComment() != null) {
            score += apArticle.getComment() * ArticleConstants.HOT_ARTICLE_COMMENT_WEIGHT;
        }
        //收藏  *8
        if (apArticle.getCollection() != null) {
            score += apArticle.getCollection() * ArticleConstants.HOT_ARTICLE_COLLECTION_WEIGHT;
        }

        return score;
    }
}
